package com.example.rabbitmq_study.workqueue;

import com.example.rabbitmq_study.util.RabbitmqUtil;
import com.rabbitmq.client.*;
import sun.plugin2.os.windows.FLASHWINFO;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author Huangyt
 * @version 1.0
 * @date 2020/7/28 22:00
 */
public class Consumer1 {
    public static void main(String[] args) throws IOException, TimeoutException {
        //获取连接
        Connection connection = RabbitmqUtil.getConnection();
        //创建通道
        Channel channel = connection.createChannel();
        //声明队列
        channel.queueDeclare("work"/*队列名*/, true/*持久化*/, false/*独占*/, false/*自动删除*/, null/*map额外参数*/);
        //设置消费者通道每次只能接收一条消息，防止一次性全部被分配
        channel.basicQos(1);
        //接收消息
        channel.basicConsume("work", false, new DefaultConsumer(channel){
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //获取交换机
                String exchange = envelope.getExchange();
                //消息id，mq在channel中用来标识消息的id，如果获取到该id表明也获取到了该id的消息所以可用于确认消息已接收
                long deliveryTag = envelope.getDeliveryTag();
                //将字节类型的消息转换成字符串
                String string = new String(body, "utf-8");

                System.out.println("receive deliveryTag:" + deliveryTag);
                System.out.println("消费者1——receive message:" + string);

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                /*
                    参数1：获取该消息的deliveryTag，确认具体的哪一个消息d
                    参数2：是否批量. true：将一次性ack所有小于deliveryTag的消息。
                 */
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        });
    }
}
